<?php namespace Home\Controller; 
use Hdphp\Controller\Controller;
use Common\Model\Cate;
use Common\Model\Goods;
use Common\Model\Goods_attr;
use Common\Model\Type_attr;
//列表页控制器
class ListController extends CommonController{
    //载入列表页面
    public function index(){
    	if(IS_POST){
    		$select=Q('post.select');
			if($select){
				$goodsModel=new Goods;
				$goodsData=$goodsModel->where("gname like '%{$select}%'")->get();
	    		View::with('goodsData',$goodsData);
			}else{
				View::with('goodsData',[]);
			}
    	}else{
	    	$cid=Q('get.cid',0,'intval');
			$cateModel=new Cate;
			//显示所在位置
			$caData=$cateModel->where("cid={$cid}")->find();
			View::with('caData',$caData);
			//获取当前顶级分类的所有子分类的cid
			$cids=$cateModel->getSon($cateModel->get(), $cid);
			//压入当前cid
			$cids[]=$cid;
			//根据cid获得所有的商品的gid
			$goodsModel=new Goods;
			$gids=$goodsModel->where("shop_category_cid IN (".implode(',', $cids).")")->lists('gid');
			//根据所有的gid查询商品属性表
			if($gids){
				$goodAttrModel=new Goods_attr;
				//并组合去重
				$goodsAttr=$goodAttrModel->where("shop_goods_gid IN (".implode(',', $gids).")")->groupBy('gavalue')->get();
				//把相同taid的属性放在一起
				$sameTamp=[];
				foreach($goodsAttr as $v){
					$sameTamp[$v['shop_type_attr_taid']][]=$v;
				}
				//组合名字和值
				$fallAttr=[];
				foreach($sameTamp as $taid=>$v){
					$type_attrModel=new Type_attr;
					$name=$type_attrModel->where("taid={$taid}")->pluck('taname');
					$fallAttr[]=[
						'name'=>$name,
						'value'=>$v
					];
				}	
	//			p($fallAttr);
				View::with('fallAttr',$fallAttr);
				/*筛选效果*/
				//1、地址栏效果
				//(1)获取$fallAttr的数量
				$num=count($fallAttr);
				//进行组合
				$param=isset($_GET['param'])?explode('_', $_GET['param']):array_fill(0,$num,0);
	//			p($param);
				View::with('param',$param);
				//(2)筛选，确定最终的商品id
				$finalGids=$this->filter($param,$gids);
	//			p($finalGids);
				//(3)根据最终的商品id进行查询，获取筛选的商品
				if($finalGids){
					$goodsData=$goodsModel->where("gid IN (".implode(',', $finalGids).")")->get();
				}else{
					$goodsData=[];
				}
				View::with('goodsData',$goodsData);
			}else{
				View::with('fallAttr',[]);
				View::with('goodsData',[]);
			}
		}
    	View::make();
	}
	//进行筛选，获取最终的商品id
	private function filter($param,$cidGids){
		$goodsAttrModel=new Goods_attr;
		$gidArr=[];
		foreach($param as $gaid){
			//如果点击的全部是”不限“的话不执行查询
			if($gaid){
				//根据gaid查询商品属性的名称
				$gavalue=$goodsAttrModel->where("gaid={$gaid}")->pluck('gavalue');
				//根据$gavalue查询对应的商品gid
				$gidArr[]=$goodsAttrModel->where("gavalue='{$gavalue}'")->lists('shop_goods_gid');
			}
		}
//		p($gidArr);
//		p($cidGids);
		if($gidArr){
			$gid=$gidArr[0];
			//进行数组取交集
			foreach($gidArr as $v){
				$gid=array_intersect($v,$gid);
			}
			//因为$gaid可能会有其他分类的gaid ，所以要确保为当前分类，要再次进行取交集
			$finalGids=array_intersect($gid,$cidGids);
//			p($finalGids);
		}else{//如果全是'不限'的时候
			$finalGids=$cidGids;
		}
		return  $finalGids;
	}
	
}
?>